<template>
  <div class="editor-container">
    <!-- @input="$emit('input', $event.target.value)" -->
    <textarea :id="editorId" class="tinymce-textarea" :value="modelValue"></textarea>
    <!-- 这个 hidden 的 input 作用是：当点击编辑器中自定义的按钮 imgBtn 时，触发这个 input 的click 事件，就会弹窗显示选择文件。 -->
    <input ref="uploadRef" type="file" hidden accept=".jpg,.jpeg,.png,.bmp,.svg" @change="onFileChange" />

    <!-- <textarea :value="modelValue" @input="$emit('input', $event.target.value)"></textarea> -->
  </div>
</template>

<script>
  import options from "./options"

  function init(editorId, modelValue, that) {
    console.warn("init", editorId, modelValue);
    window.tinymce.init({
      ...options,
      min_height: 600,
      selector: `#${editorId}`,

      init_instance_callback(editor) {
        // if (!hasInit) {
        //   editor.setContent(modelValue || '');
        // }
        // hasInit = true;
        editor.on('NodeChange Change KeyUp SetContent', (data) => {
          console.log("NodeChange Change KeyUp SetContent data", data, data.type);
          console.log("NodeChange Change KeyUp SetContent", editor.getContent());
          // emit('update:modelValue', editor.getContent());
          that.$emit('input', editor.getContent());
        });
      },
      setup(editor) {
        editor.ui.registry.addButton('imgbtn', {
          // text: '',
          // 图标 \tinymce\icons\default\icons.min.js
          icon: 'image',
          tooltip: '插入图片',
          onAction: () => {
            that.$refs.uploadRef.click();
          },
        });
      },

      images_upload_url: 'http://www.tp505.cm/index.php?s=index/file/save',
      // 拦截截图并上传，防止base64导致内容超长
      /* async images_upload_handler(blobInfo) {
        const file = new File([blobInfo.blob()], 'cut.jpg');
        const formData = new FormData();
        formData.append('file', file);
        // const res = await upload(formData)
        // return res.url
      }, */
    });
  }

  function getEditor(editorId) {
    return window.tinymce.get(editorId);
  }

  function destroy(editorId) {
    const tinymce = window.tinymce.get(editorId);
    if (tinymce) {
      tinymce.destroy();
    }
  }

  function setContent(editorId, value) {
    const editor = window.tinymce.get(editorId);
    editor.setContent(value);
  }

  function getContent(editorId) {
    const editor = window.tinymce.get(editorId);
    return editor.getContent();
  }

  function getHash(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
      const char = str.charCodeAt(i);
      hash = (hash << 5) - hash + char;
      hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
  }

  export default {
    name: "TinymceEditor",
    /* props: {
      modelValue: {
        type: String,
        default: '',
      }
    }, */
    props: ['modelValue'], // 这里 'value' 是 prop，对应于 v-model 的绑定值
    model: {
      prop: 'modelValue', // 表示 v-model 绑定的 prop 是 modelValue
      event: 'input' // 表示更新这个值时触发 input 事件
    },
    data() {
      return {
        obj: null,
        editorId: `winter_${Math.ceil(Math.random() * 1000000)}`
      }
    },
    watch: {
      modelValue(val1, val2) {
        console.warn("watch modelValue", val1, val2);
      }
    },
    methods: {
      async onFileChange(e) {
        const file = e.target.files[0];
        const size = file.size;
        if (size > 2 * 1024 * 1024) {
          $message.warning('图片资源不能大于2M');
        } else {
          const formData = new FormData();
          formData.append('file', file);
          // const img = await fileToBase64(file)
          // window.tinymce.get(id.value).insertContent(`<img class="wscnph" src="${img}" >`)
          let res = await upload(formData);
          window.tinymce.get(editorId).insertContent(`<img style="max-width: 100%" class="wscnph" src="${res.url}" >`);
        }
      }
    },
    computed: {
      //
    },
    mounted() {
      console.log("onMounted");
      // console.log("this.$emit", this.$emit);
      // console.log("this.$refs", this.$refs);
      init(this.editorId, this.modelValue, this);
      // var _that = this;
      // setInterval(() => {
      //   getEditor(_that.editorId).setContent(new Date().toLocaleString());
      // }, 3000);
    },
    unmounted() {
      destroy();
    },
  }
</script>

<style scoped>
  .editor-container {
    width: 100%;
  }
</style>